using System;
using Audio;
using UnityEngine;
using Utils;
using Random = UnityEngine.Random;

namespace Combat
{
    public class Weapon : MonoBehaviour
    {
        public static Action<Team, Weapon> AnyWeaponFired;
        
        public float RecoilForce => recoilForce;
        
        [SerializeField] private Transform muzzle;
        [SerializeField] private ParticleSystem shootEffect;
        [SerializeField] private AudioClip fireSound;
        
        [SerializeField] private float shootInterval = 0.5f;
        [SerializeField] private float recoilForce = 0.5f;
        [SerializeField] private float bulletSpreadDegree = 5f;
        
        private Entity _entity;
        private ILauncher _launcher;
            
        private Timer _coolingTimer;
        

        private void Awake()
        {
            _entity = GetComponentInParent<Entity>();
            _launcher = GetComponent<ILauncher>();
            _coolingTimer = new Timer(shootInterval);
        }
        
        private void Update()
        {
            _coolingTimer.Tick();
        }

        public bool TryFire(Vector3 atDirection, Vector3 aimPosition)
        {
            if (_coolingTimer.IsActive)
            {
                return false;
            }
            
            AudioPlayer.Instance.PlaySound(fireSound);
            shootEffect.Play();
            Quaternion rotation = Quaternion.Euler(0, 0, Random.Range(-bulletSpreadDegree, bulletSpreadDegree));
            _launcher.Fire(muzzle.position, rotation * atDirection,  aimPosition, _entity.Team);
            _coolingTimer.Reset();
            
            AnyWeaponFired?.Invoke(_entity.Team, this);
            return true;
        }
    }
}
